#!/usr/bin/env python
# -*- coding:utf-8 -*-


from goods.models import SKU
from rest_framework import serializers

class CartSerializer(serializers.Serializer):

    sku_id = serializers.CharField(label="商品id",required=True)
    count = serializers.IntegerField(label="个数",required=True,min_value=1)
    selected = serializers.BooleanField(label="是否选项",default=True,required=False)

    def validate(self, attrs):

        sku_id = attrs.get("sku_id")
        count = attrs.get("count")
        # 判断商品是否存在
        try:
            sku = SKU.objects.get(pk=sku_id)
        except SKU.DoesNotExist:
            raise serializers.ValidationError("商品信息不存在")
        # 判断库存
        if count > sku.stock:
            raise serializers.ValidationError("库存不足")

        return attrs


from rest_framework import serializers
from goods.models import SKU

class CartSKUSerializer(serializers.ModelSerializer):

    count = serializers.IntegerField(label='数量')
    selected = serializers.BooleanField(label='是否勾选')

    class Meta:
        model = SKU
        fields = ('id','count', 'name', 'default_image_url', 'price', 'selected')


class CartDeleteSerializer(serializers.Serializer):

    sku_id = serializers.CharField(label="商品id",required=True)

    def validate(self, attrs):

        sku_id = attrs.get("sku_id")
        try:
            sku = SKU.objects.get(pk=sku_id)
        except Exception:
            raise serializers.ValidationError('商品信息不存在')

        return attrs


